package com.spark.common.upload.service;

import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.spark.common.upload.StorageService;
import com.spark.common.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;


/**
 * 七牛云实现
 *
 * @author LYCHEE
 * @date 2025/3/13 10:25
 */
@Configuration
@ConditionalOnProperty(name = "upload.type", havingValue = "qiniu")
public class QiniuStorageService implements StorageService {


    @Value("${upload.qiniu.access-key}")
    private String accessKey;
    @Value("${upload.qiniu.secret-key}")
    private String secretKey;
    @Value("${upload.qiniu.bucket}")
    private String bucket;
    @Value("${upload.qiniu.domain}")
    private String domain;

    private com.qiniu.storage.Configuration cfg;
    private UploadManager uploadManager;

    @PostConstruct
    public void init() {
        cfg = new com.qiniu.storage.Configuration(Region.autoRegion());
        uploadManager = new UploadManager(cfg);
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        String fileName = FileUploadUtils.codingFileName(file);
        String token = Auth.create(accessKey, secretKey).uploadToken(bucket);
        uploadManager.put(file.getBytes(), fileName, token);
        return getFileUrl(fileName);
    }

    @Override
    public String getFileUrl(String fileName) {
        return domain + "/" + fileName;
    }
}
